import 'package:flame/extensions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:getwidget/getwidget.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:points24/db/GameData.dart';
import 'package:points24/domain/save_result.dart';
import 'package:points24/ext_widget/widget_util.dart';

class HistoryPage extends StatefulWidget {
  const HistoryPage({super.key});

  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  var history = <SaveResult>[];
  int expandIndex = -1;
  String sumText = "";

  int successTimes = 0;
  int failTimes = 0;
  double totalSuccessTime = 0;
  double successAvgTime = 0;

  @override
  void initState() {
    super.initState();

    Future.delayed(const Duration(milliseconds: 500), () async {
      history = await GameData.readAllData();

      for (SaveResult saveResult in history) {
        if (saveResult.isSuccess()) {
          totalSuccessTime += saveResult.costTime;
          successTimes++;
        } else {
          failTimes++;
        }
      }
      successAvgTime =successTimes==0?0: totalSuccessTime / successTimes;
      sumText = " Success:${successTimes} VS Fail:${failTimes} ";

      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
            onTapUp: (x) {
              Navigator.of(context).pop();
            },
            child: const Icon(
              Icons.arrow_back_rounded,
              color: Colors.white,
            )),
        title: Text("History ${history.length} times"),
      ),
      body: Column(
        children: [
          Container(
            height: 50,
            width: double.infinity,
            color: Colors.blue,
            margin: EdgeInsets.all(10.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [

                const Icon(Icons.thumb_up, color: Colors.amberAccent),
                SizedBox(width: 5.w,),
                Text("${successTimes}"),
                Container(
                    margin: EdgeInsets.only(left: 10.w, right: 10.w),
                    child: const Icon(
                      Icons.tour,
                      color: Colors.cyanAccent,
                    )),
                Text("${failTimes}"),
                SizedBox(width: 5.w,),
                const Icon(
                  Icons.thumb_down,
                  color: Colors.red,
                ),

                Container(
                    padding: EdgeInsets.all(10.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("Avg Time:${(successAvgTime / 1000).toInt()}s",style: GoogleFonts.poppins(
                          fontWeight: FontWeight.w500,
                          fontSize: 14.sp
                        ),),
                      ],
                    )),
              ],
            ),
          ),

          Expanded(
            child: Container(
              color: Colors.blue,
              child: ListView.separated(
                  padding: EdgeInsets.only(top: 10.h),
                  itemBuilder: (ctx, index) {
                    var item = history[index];

                    return Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.r),
                          color: Colors.white,
                          gradient: const LinearGradient(colors: [Colors.white, Colors.white70])),
                      width: double.infinity,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            alignment: Alignment.center,
                            margin: EdgeInsets.only(left: 15.w, right: 15.w),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                item.isSuccess()
                                    ? Icon(
                                        Icons.thumb_up,
                                        color: Colors.amberAccent,
                                        size: 30.w,
                                      )
                                    : Icon(
                                        Icons.thumb_down,
                                        color: Colors.red,
                                        size: 30.w,
                                      ),
                                SizedBox(
                                  width: 10.w,
                                ),
                                Text(
                                  "${item.rowNo}",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.poppins(color: Colors.black, fontSize: 14.sp, fontWeight: FontWeight.w500),
                                ),
                                Text(
                                  "Time:${item.costTime / 1000}s",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.poppins(color: Colors.black, fontSize: 14.sp, fontWeight: FontWeight.w500),
                                ),
                                GFButton(
                                    text: "Try Again",
                                    textStyle: GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 11.sp, color: Colors.white),
                                    borderSide: BorderSide(color: item.isSuccess() ? Colors.amberAccent : Colors.red, width: 2),
                                    shape: GFButtonShape.pills,
                                    onPressed: () {
                                      showTryAgain(context, item.rowNo);
                                      debugPrint("Try agin-> ${item.rowNo}");
                                    })
                              ],
                            ),
                          ),
                          Offstage(
                            offstage: !(expandIndex == index),
                            child: Column(
                              children: [
                                Container(
                                  padding: EdgeInsets.all(10.w),
                                  width: double.infinity,
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: item.winSteps.map<Widget>((e) {
                                      return Text(
                                        "${e.niceExpress()}",
                                        style: GoogleFonts.poppins(color: Colors.black, fontSize: 15.sp, fontWeight: FontWeight.w600),
                                      );
                                    }).toList(),
                                  ),
                                ),
                                Container(
                                    alignment: Alignment.bottomRight,
                                    margin: EdgeInsets.only(right: 15.w),
                                    child: GFButton(
                                      shape: GFButtonShape.pills,
                                      onPressed: () {
                                        deleteRecord(index);
                                      },
                                      text: "Delete",
                                      color: Colors.red,
                                      borderSide: const BorderSide(color: Colors.red, width: 2),
                                      textStyle: GoogleFonts.poppins(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.yellow,
                                        fontSize: 12.sp,
                                      ),
                                    ))
                              ],
                            ),
                          ),
                        ],
                      ),
                    ).prop(
                        margins: [15.w, 0, 15.w, 0],
                        onTap: () {
                          if (expandIndex == index) {
                            expandIndex = -1;
                          } else {
                            expandIndex = index;
                          }

                          debugPrint("Steps");
                          setState(() {});
                        });
                  },
                  separatorBuilder: (ctx, index) {
                    return SizedBox(height: 10.h);
                  },
                  itemCount: history.length),
            ),
          ),
        ],
      ),
    );
  }

  void deleteRecord(int index) {
    history.removeAt(index);
    expandIndex = -1;
    //重新保存
    setState(() {});

    var savedResult = List.of(history);
    savedResult.reverse();
    GameData.reSaveAllResultContent(savedResult);
  }

  void showTryAgain(BuildContext context, List<dynamic> rowNo) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          content: Container(
              height: 60.h,
              alignment: Alignment.center,
              child: Text(
                textAlign: TextAlign.center,
                '${rowNo}\nTry this again?',
                style: GoogleFonts.poppins(fontSize: 20.sp, fontWeight: FontWeight.w500, color: Colors.blue),
              )),
          actionsAlignment: MainAxisAlignment.spaceBetween,
          actions: <Widget>[
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Cancel',
                color: Colors.grey,
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.black),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Again',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop();
                  Navigator.of(context).pop({"rowNo": rowNo});
                }),
          ],
        );
      },
    );
  }
}
